#include "qanimalgraphicsitem.h"

#include <QPainter>
#include <cassert>

#include "qlife.h"
#include "qanimal.h"

QAnimalGraphicsItem::QAnimalGraphicsItem ( QAnimal* animal, QColor color ) : QLifeGraphicsItem ( ( QLife* ) animal )
{
	assert ( animal != NULL );
	assert ( &color != NULL );

	this -> animal = animal;
	this -> color = color;

	// CHILDREN
	destLine = new QGraphicsLineItem ( this, scene() );
	destLine -> setVisible ( false );

	enemyLine = new QGraphicsLineItem ( this, scene() );
	enemyLine -> setPen ( QPen ( QBrush ( color ), 2 ) );
	enemyLine -> setVisible ( false );

	viewEllipse = new QGraphicsEllipseItem ( this, scene() );
	viewEllipse -> setVisible ( false );

	advance ( 0 );
}

QAnimalGraphicsItem::~QAnimalGraphicsItem()
{}

void QAnimalGraphicsItem::advance ( int phase )
{
	if ( phase == 0 )
	{
		// set position
		setPos ( animal -> getX(), animal -> getY() );

		// calculate color
		float e = animal -> getEnergy();

		// e can be beyond it's borders
		if ( e < 0 ) e = 0;
		if ( e > 255 ) e = 255;

		//color = QColor((((int)e * 255) / 150), 0, (255 - (((int)e * 255) / 150)), 128);

		// selection
		if ( isSelected() )
		{
			setPen ( QPen ( color, 4 ) );
			setBrush ( color );
		}
		else
		{
			setPen ( color );
			setBrush ( color );
		}

		// draw different goodies
		if ( animal -> isAlive() )
		{
			// fighting line
			if ( animal -> isFighting() )
			{
				float xDest = animal -> getEnemy() -> getX() - x();
				float yDest = animal -> getEnemy() -> getY() - y();

				enemyLine -> setLine ( QLineF ( 0, 0, xDest, yDest ) );
				enemyLine -> setVisible ( true );
			}
			else
			{
				enemyLine -> setVisible ( false );
			}

			// destination line
			if ( drawDestination )
			{
				float xDest = animal -> getXDest() - x();
				float yDest = animal -> getYDest() - y();

				destLine -> setLine ( QLineF ( 0, 0, xDest, yDest ) );
				destLine -> setVisible ( true );
			}
			else
			{
				destLine -> setVisible ( false );
			}

			// view distance
			if ( drawViewDistance )
			{
				float vDist = animal -> getViewDistance();

				viewEllipse -> setRect ( QRectF ( -vDist, -vDist, 2 * vDist, 2 * vDist ) );
				viewEllipse -> setVisible ( true );
			}
			else
			{
				viewEllipse -> setVisible ( false );
			}
		}
		else
		{
			enemyLine -> setVisible ( false );
			destLine -> setVisible ( false );
			viewEllipse -> setVisible ( false );

			setPen ( QColor ( 128, 128, 128, 64 ) );
			setBrush ( QColor ( 128, 128, 128, 64 ) );
		}

		rect.setX ( -3 );
		rect.setY ( -3 );
		rect.setWidth ( 6 );
		rect.setHeight ( 6 );

		life -> setSelected ( isSelected() );
	}
	else if ( phase == 1 )
	{
		update ( rect );
	}
}

void QAnimalGraphicsItem::paint ( QPainter * painter, const QStyleOptionGraphicsItem*, QWidget* )
{
	painter -> setPen ( pen );
	painter -> setBrush ( brush );
	painter -> drawRect ( rect );
}
